package com.ctg.sysmgr.sso.server.service.credential.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.constraints.NotNull;

import org.jasig.cas.authentication.Credential;
import org.jasig.cas.authentication.principal.DefaultPrincipalFactory;
import org.jasig.cas.authentication.principal.Principal;
import org.jasig.cas.authentication.principal.PrincipalFactory;
import org.jasig.services.persondir.IPersonAttributeDao;
import org.jasig.services.persondir.IPersonAttributes;
import org.jasig.services.persondir.support.StubPersonAttributeDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ctg.sysmgr.sso.server.data.dao.sys.ISystemUserDao;
import com.ctg.sysmgr.sso.server.data.entity.SystemUser;
import com.ctg.sysmgr.sso.server.service.credential.ISessionPersonDirectoryPrincipal;
import com.ctg.sysmgr.sso.server.service.sys.impl.SystemUserServiceImpl;



public class SessionPersonDirectoryPrincipalResolver implements ISessionPersonDirectoryPrincipal{

	
	private ISystemUserDao systemUserDao;
	

	private final Logger log = LoggerFactory.getLogger(this.getClass());
    /** Log instance. */
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    private boolean returnNullIfNoAttributes;

    /** Repository of principal attributes to be retrieved. */
    @NotNull
    private IPersonAttributeDao attributeRepository = new StubPersonAttributeDao(new HashMap<String, List<Object>>());

    /** Factory to create the principal type. **/
    @NotNull
    private PrincipalFactory principalFactory = new DefaultPrincipalFactory();

    /** Optional principal attribute name. */
    private String principalAttributeName;

    @Override
    public boolean supports(final Credential credential) {
        return true;
    }

    public ISystemUserDao getSystemUserDao() {
		return systemUserDao;
	}

	public void setSystemUserDao(ISystemUserDao systemUserDao) {
		this.systemUserDao = systemUserDao;
	}

	
	/**
	 * 返回用户ID
	 */
	@Override
    public final Principal resolve(final Credential credential) {
        String principalId = extractPrincipalId(credential);//获取用户名
        final IPersonAttributes personAttributes = attributeRepository.getPerson(principalId);
        if (principalId == null) {
            logger.info("用户名为空");
            return null;
        }

        //返回信息的载体
        final Map<String, Object> convertedAttributes = new HashMap<String, Object>();

        /*//这种方式获取userId是不行的
        //业务系统调用服务，开发者门户调用数据库
        SystemUser user = systemUserDao.getUserByName(principalId);*/
        
        Map<String,Object> map = SystemUserServiceImpl.threadLocal.get();//获取登录成功时存储在threadLocal的map,map里边是个SystemUser
        
        SystemUser sysUser = (SystemUser) map.get("sysUser");
        
        convertedAttributes.put("userId",sysUser.getSysUserId());
        
        
        
        return this.principalFactory.createPrincipal(principalId, convertedAttributes);
    }

	
	
	
	/*
	
	 protected AuthenticationBuilder authenticateInternal(final Credential credential)
	            throws AuthenticationException {

	        final AuthenticationBuilder builder = new DefaultAuthenticationBuilder(NullPrincipal.getInstance());
	        
	        builder.addCredential(new BasicCredentialMetaData(credential));
	        
	        
	        
	        
	        boolean found;
	        Principal principal;
	        PrincipalResolver resolver;
	        
	        principal = resolver.resolve(credential);
	        
	        
	        
	    }
	*/
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
    public final void setAttributeRepository(final IPersonAttributeDao attributeRepository) {
        this.attributeRepository = attributeRepository;
    }

    public void setReturnNullIfNoAttributes(final boolean returnNullIfNoAttributes) {
        this.returnNullIfNoAttributes = returnNullIfNoAttributes;
    }

    /**
     * Sets the name of the attribute whose first non-null value should be used for the principal ID.
     *
     * @param attribute Name of attribute containing principal ID.
     */
    public void setPrincipalAttributeName(final String attribute) {
        this.principalAttributeName = attribute;
    }

    /**
     * Sets principal factory to create principal objects.
     *
     * @param principalFactory the principal factory
     */
    public void setPrincipalFactory(final PrincipalFactory principalFactory) {
        this.principalFactory = principalFactory;
    }

    /**
     * Extracts the id of the user from the provided credential. This method should be overridded by subclasses to
     * achieve more sophisticated strategies for producing a principal ID from a credential.
     *
     * @param credential the credential provided by the user.
     * @return the username, or null if it could not be resolved.
     */
    protected String extractPrincipalId(final Credential credential) {
        return credential.getId();
    }

}
